#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 注意，一定要装 pip install aioredis==1.3.1

from fastapi import FastAPI, Request, Query
from aioredis import Redis, create_redis_pool


app = FastAPI(debug=True)



async def create_redis() -> Redis:
    return await create_redis_pool("redis://localhost:6379", db=0, password=None, encoding="utf-8")


async def startup_event():
    app.state.redis = await create_redis()
    print("init redis success")

app.add_event_handler("startup", startup_event)


async def shutdown_event():
    app.state.redis.close()
    await app.state.redis.wait_closed()
    print("redis closed")

app.add_event_handler("shutdown", shutdown_event)


@app.get("/test", summary="test redis")
async def test_redis(request: Request, num: int = Query(123, title="参数num")):
    """
    等待redis写入，await异步变同步
    如果不关心结果可以不用await，但是这里下一步要取值
    必须得先等存完值，然后再取
    """
    await request.app.state.redis.set("test", num)
    # 等待读取值
    value = await request.app.state.redis.get("test")
    print(value, type(value))
    return {"value": value}







if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)